import sha1 from 'crypto-js/sha1';
import md5 from 'crypto-js/md5';
import {registerRequestParamsProcessor, submitMultipartFormData} from "./redare/utils/Request";

let apiKey;

export function appApiInit({key} = {}) {
    apiKey = key;
    registerRequestParamsProcessor(requestParamsProcessor);
}

const API_CONFIG = {
    uploadImgUrl: `${window._ctxRes}/image`,
    uploadFileUrl: `${window._ctxRes}/file`,
};

export function uploadImage({file, base64}) {
    return submitMultipartFormData({
        url: API_CONFIG.uploadImgUrl,
        bodyParams: {
            file,
            base64
        },
        mode: 'cors'
    });
}

export function uploadFile(file) {
    return submitMultipartFormData({
        url: API_CONFIG.uploadFileUrl,
        bodyParams: {
            file
        },
        mode: 'cors'
    });
}

const requestParamsProcessor = ({url, bodyParams, urlParams, headers}) => {
    let tmpUrl = url.toLowerCase();
    if (!tmpUrl.startsWith('http://') && !tmpUrl.startsWith('https://')) {
        if (url !== API_CONFIG.uploadImgUrl && url !== API_CONFIG.uploadFileUrl) {
            url = `${window._ctxApi}${url}`;
        }
    }
    let signParams = signatureParams();
    urlParams = {
        ...urlParams,
        ...signParams,
    };
    return {url, bodyParams, urlParams, headers};
};

function signatureParams() {
    let key = apiKey;
    if (key) {
        key = parseKey(key);
    }
    let timestamp = String(new Date().getTime());
    let nonce = md5(`${timestamp}${Math.random()}`);
    let signature = sha1([key, timestamp, nonce].sort().join('')).toString();
    return {
        _timestamp: timestamp,
        _nonce: nonce,
        _signature: signature,
    };
}

export function parseKey(key) {
    return key.substring(5, key.length - 6);
}